package api

import (
	"net/http"
	"gitee.com/DengAnbang/Computation/src/dbops"
	"gitee.com/DengAnbang/Computation/src/bean"
	"gitee.com/DengAnbang/Computation/src/util"
)

func CreateTreeHttp(_ http.ResponseWriter, r *http.Request) error {
	treeName := util.GetValueFormRequest(r, "treeName")
	createdId := util.GetValueFormRequest(r, "createdId")
	sort := util.GetValueFormRequest(r, "sort")
	thisCode := util.GetValueFormRequest(r, "code")
	typeTree := util.GetValueFormRequest(r, "typeTree")
	tree, err := dbops.CreateTree(treeName, createdId, typeTree, sort, thisCode, "")
	if err != nil {
		return err
	}
	return bean.NewSucceedMessage(tree)
}
func AddTreeNodeHttp(_ http.ResponseWriter, r *http.Request) error {
	treeName := util.GetValueFormRequest(r, "treeName")
	nodeParentId := util.GetValueFormRequest(r, "nodeParentId")
	createdId := util.GetValueFormRequest(r, "createdId")
	sort := util.GetValueFormRequest(r, "sort")
	thisCode := util.GetValueFormRequest(r, "code")
	no := util.GetValueFormRequest(r, "no")
	tree, err := dbops.AddTreeNode(treeName, nodeParentId, createdId, sort, thisCode, no)
	if err != nil {
		return err
	}
	return bean.NewSucceedMessage(tree)
}

func DeleteTreeNodeHttp(_ http.ResponseWriter, r *http.Request) error {
	nodeId := util.GetValueFormRequest(r, "nodeId")
	err := dbops.DeleteTreeNode(nodeId)
	if err != nil {
		return err
	}
	return bean.NewSucceedMessage("删除成功")
}

func SelectTreeNodeListHttp(_ http.ResponseWriter, r *http.Request) error {
	nodeId := util.GetValueFormRequest(r, "nodeId")
	beans, err := dbops.SelectTreeNodeList(nodeId, true)
	if err != nil {
		return err
	}
	return bean.NewSucceedMessage(beans)
}

func RenameTreeNodeHttp(_ http.ResponseWriter, r *http.Request) error {
	nodeId := util.GetValueFormRequest(r, "nodeId")
	newName := util.GetValueFormRequest(r, "newName")
	beans, err := dbops.RenameTreeNode(nodeId, newName)
	if err != nil {
		return err
	}
	return bean.NewSucceedMessage(beans)
}

func GetMyTreeNodeHttp(_ http.ResponseWriter, r *http.Request) error {
	userId := util.GetValueFormRequest(r, "userId")
	typeTree := util.GetValueFormRequest(r, "typeTree")
	var tree bean.TreeBean
	trees, err := dbops.GetUserTreeList(userId, typeTree)
	if err != nil {
		return err
	}
	for _, v := range trees {
		if v.CreatedId == userId {
			tree = v.TreeBean
			break
		}
	}
	if len(tree.NodeId) <= 0 {
		return bean.NewSucceedMessage(nil)
	}
	beans, err := dbops.SelectTreeNodeList(tree.TreeId, true)
	if err != nil {
		return err
	}
	return bean.NewSucceedMessage(beans)
}
func GetUserTreeListHttp(_ http.ResponseWriter, r *http.Request) error {
	userId := util.GetValueFormRequest(r, "userId")
	typeTree := util.GetValueFormRequest(r, "typeTree")
	beans, err := dbops.GetUserTreeList(userId, typeTree)
	if err != nil {
		return err
	}
	return bean.NewSucceedMessage(beans)
}
